{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "3649dba3",
   "metadata": {},
   "source": [
    "# 逆Z变换"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "a658940b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0.         0.33333333 0.44444444 0.48148148 0.49382716 0.49794239]\n",
      "[  0.   1.   4.  13.  40. 121.]\n"
     ]
    }
   ],
   "source": [
    "#采用长除法求逆z变换，求出逆变换后依次x（n）的系数\n",
    "import numpy as np\n",
    "from math import *\n",
    "def longdiv(num,den,side,length):#numerator为分子，denominator为分母\n",
    "    # side确定序列为左边序列还是右边序列（结合收敛域），length：想要输出的逆变换后x(n)系数的长度\n",
    "  L=np.arange(length)\n",
    "  if side =='left':\n",
    "     den=np.flipud(den)\n",
    "     #如果求|Z|<RX-收敛域内的Z逆变换，即为左边序列，则将分母的系数倒序计算,即升幂除法\n",
    "  if len(den)<len(num):\n",
    "    print('error z transform')#如果分子的z的阶次大于分母则有误\n",
    "  if len(num)!=len(den):\n",
    "    num=np.append(np.zeros([len(den)-len(num),1]),num)\n",
    "    res=[]\n",
    "    m=num\n",
    "  for i in L:\n",
    "    tempRes=m[0]/den[0]#长除\n",
    "    m=m-tempRes*den\n",
    "    m=np.append(m[1:len(m)],0)\n",
    "    res=np.append(res,tempRes)\n",
    "  print(res)\n",
    "#数组最右端为z的零次的系数，依次往左为更高阶次z次幂的系数\n",
    "#X(Z)=Z/(3Z^2-4Z+1)\n",
    "longdiv(np.array([1,0]),np.array([3,-4,1]),'right',6)\n",
    "longdiv(np.array([1,0]),np.array([3,-4,1]),'left',6)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "13c81975",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
